package com.xyzq.hs;

import java.util.ArrayList;
import java.util.List;

import com.xyzq.hs.util.ByteUtils;
import com.xyzq.hs.util.Logger;
import com.xyzq.hs.util.LoggerFactory;

public class Request {
	
	Logger log=LoggerFactory.getLogger(Request.class);
	
	private Header header = null;
	
	private byte[] commandCount=null;
	
	private List<RequestEntry> entries=null;
	
	private final static int MAX_REQUEST_COMMAND_COUNT=32;
	
	public Request(RequestEntry entry) {
		this.entries=new ArrayList<RequestEntry>();
		entries.add(entry);
	}
	
	public Request(List<RequestEntry> entries) {
		if(entries.size()>MAX_REQUEST_COMMAND_COUNT){
			throw new IllegalArgumentException("Request command counts exceed the limit["+MAX_REQUEST_COMMAND_COUNT+"].");
		}
		this.entries=entries;
	}

	public byte[] getMessage() {
		int entrySize = 0;
		for (RequestEntry entry : entries) {
			entrySize+=entry.asBytes().length;
		}
		
		commandCount = ByteUtils.short2byte((short)entries.size());
		
		header = new Header(entrySize, Header.HEADER_BODYTYPE_REQUEST);
		
		int messageSize = Header.HEADER_SIZE + commandCount.length+entrySize;
		
		byte[] message = new byte[messageSize];
		
		//add header
		ByteUtils.copy(header.asBytes(), 0, message, 0, Header.HEADER_SIZE);
		int destPos = Header.HEADER_SIZE;
		//add commandCount
		ByteUtils.copy(commandCount, 0, message, destPos, commandCount.length);
		//add requestEntry byte
		destPos +=commandCount.length;
		for (RequestEntry entry : entries) {
			byte[] entryByte = entry.asBytes();
			ByteUtils.copy(entryByte, 0, message, destPos, entryByte.length);
			destPos+=entryByte.length;
		}
		return message;
	}

	public Header getHeader() {
		return header;
	}
	
	
}
